package cn.yuanqiao.archive.collection.danganjieshou.service.impl;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.bianyan.utils.PictureUploadUtils;
import cn.yuanqiao.archive.collection.danganjieshou.domain.YqGcReceiveEfile;
import cn.yuanqiao.archive.collection.danganjieshou.domain.YqGcReceiveFile;
import cn.yuanqiao.archive.collection.danganjieshou.domain.YqGcReceiveFolder;
import cn.yuanqiao.archive.collection.danganjieshou.mapper.YqGcReceiveEfileMapper;
import cn.yuanqiao.archive.collection.danganjieshou.mapper.YqGcReceiveFileMapper;
import cn.yuanqiao.archive.collection.danganjieshou.mapper.YqGcReceiveFolderMapper;
import cn.yuanqiao.archive.collection.danganjieshou.service.IYqGcReceiveService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 馆藏文件接收Service业务层处理
 *
 * @ProjectName: JZSDAS
 * @Package: cn.yuanqiao.collection.danganjieshou.service.impl
 * @ClassName: YqGcReceiveServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2023/8/2 15:12
 * @Version: 1.0
 */
@Service
public class YqGcReceiveServiceImpl implements IYqGcReceiveService {
    @Autowired
    private YqGcReceiveFolderMapper yqGcReceiveFolderMapper;

    @Autowired
    private YqGcReceiveFileMapper yqGcReceiveFileMapper;

    @Autowired
    private YqGcReceiveEfileMapper yqGcReceiveEfileMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    /**
     * 查询组卷信息列表
     *
     * @param yqGcReceiveFolder
     * @return,`
     */
    @Override
    public List<YqGcReceiveFolder> selectFolder(YqGcReceiveFolder yqGcReceiveFolder) {
        return yqGcReceiveFolderMapper.selectYqGcReceiveFolderList(yqGcReceiveFolder, new YqGcReceiveFolder().getTableName());
    }

    /**
     * 查询卷内件信息列表
     *
     * @param yqGcReceiveFile
     * @return
     */
    @Override
    public List<YqGcReceiveFile> selectFile(YqGcReceiveFile yqGcReceiveFile) {
        return yqGcReceiveFileMapper.selectYqGcReceiveFileList(yqGcReceiveFile, new YqGcReceiveFile().getTableName());
    }

    /**
     * 查询组卷信息详情
     *
     * @param id
     * @return
     */
    @Override
    public YqGcReceiveFolder selectFolderId(String id) {
        return yqGcReceiveFolderMapper.selectYqGcReceiveFolderById(id, new YqGcReceiveFolder().getTableName());
    }

    /**
     * 查询卷内件信息详情
     *
     * @param id
     * @return
     */
    @Override
    public YqGcReceiveFile selectFileId(String id) {
        YqGcReceiveFile yqGcReceiveFile = yqGcReceiveFileMapper.selectYqGcReceiveFileById(id,
                new YqGcReceiveFile().getTableName());
        //查询关联附件
        yqGcReceiveFile.setEfileList(yqGcReceiveEfileMapper.selectYqGcReceiveEfileByFileId(id,
                new YqGcReceiveEfile().getTableName()));
        return yqGcReceiveFile;
    }


    /**
     * 组卷著录
     *
     * @param yqGcReceiveFolder
     * @return
     */
    @Override
    public String insertFolder(YqGcReceiveFolder yqGcReceiveFolder) {
        if (verifyFolder(yqGcReceiveFolder)) {
            throw new ServiceException("卷资料号已经存在,请修改");
        }
        String id = String.valueOf(SnowflakeIdGenerator.generateId());
        yqGcReceiveFolder.setId(id);
        yqGcReceiveFolder.setCreateTime(DateUtils.getNowDate());
        yqGcReceiveFolder.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
        yqGcReceiveFolderMapper.insertYqGcReceiveFolder(yqGcReceiveFolder, yqGcReceiveFolder.getTableName());
        return id;
    }

    /**
     * 卷内件著录
     *
     * @param yqGcReceiveFile
     * @return
     */
    @Override
    public int insertFile(YqGcReceiveFile yqGcReceiveFile) {
        if (verifyFile(yqGcReceiveFile)) {
            throw new ServiceException("件号已经存在,请修改");
        }
        String id = String.valueOf(SnowflakeIdGenerator.generateId());
        yqGcReceiveFile.setId(id);
        yqGcReceiveFile.setCreateTime(DateUtils.getNowDate());
        yqGcReceiveFile.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
        //先新增附件
        if (yqGcReceiveFile.getEfileList() != null && yqGcReceiveFile.getEfileList().size() > 0) {
            insertEFile(yqGcReceiveFile.getEfileList(), id, "1");
        }
        return yqGcReceiveFileMapper.insertYqGcReceiveFile(yqGcReceiveFile, yqGcReceiveFile.getTableName());
    }

    /**
     * 修改组卷信息
     *
     * @param yqGcReceiveFolder
     * @return
     */
    @Override
    public int updateFolder(YqGcReceiveFolder yqGcReceiveFolder) {
        if (verifyFolder(yqGcReceiveFolder)) {
            throw new ServiceException("卷资料号已经存在,请修改");
        }
        yqGcReceiveFolder.setLastupdater(String.valueOf(SecurityUtils.getUserId()));
        yqGcReceiveFolder.setLastupdateTime(DateUtils.getTime());
        if("0".equals(yqGcReceiveFolder.getControlType())){
            yqGcReceiveFileMapper.updateYqGcReceiveFileByFolderId("0",yqGcReceiveFolder.getId(),new YqGcReceiveFile().getTableName());
        }
        return yqGcReceiveFolderMapper.updateYqGcReceiveFolder(yqGcReceiveFolder, yqGcReceiveFolder.getTableName());
    }

    /**
     * 修改组件信息
     *
     * @param yqGcReceiveFile
     * @return
     */
    @Override
    public int updateFile(YqGcReceiveFile yqGcReceiveFile) {
        if (verifyFile(yqGcReceiveFile)) {
            throw new ServiceException("件号已经存在,请修改");
        }
        yqGcReceiveFile.setLastupdater(String.valueOf(SecurityUtils.getUserId()));
        yqGcReceiveFile.setLastupdateTime(DateUtils.getTime());
        //判断是否需要修改附件信息
        if (yqGcReceiveFile.getEfileList() != null && yqGcReceiveFile.getEfileList().size() > 0) {
            insertEFile(yqGcReceiveFile.getEfileList(), yqGcReceiveFile.getId(), "2");
        }
        return yqGcReceiveFileMapper.updateYqGcReceiveFile(yqGcReceiveFile, yqGcReceiveFile.getTableName());
    }


    /**
     * 删除组卷信息
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int delFolder(String[] ids) {
        //查询卷内件信息
        List<YqGcReceiveFile> yqGcReceiveFiles = yqGcReceiveFileMapper.selectYqGcReceiveFileByFolderId(ids,
                new YqGcReceiveFile().getTableName());
        if (yqGcReceiveFiles != null && yqGcReceiveFiles.size() > 0) {
            //删除卷内件信息
            yqGcReceiveFileMapper.deleteYqGcReceiveFileByfolderIds(ids, new YqGcReceiveFile().getTableName());
            List<String> fileIds = yqGcReceiveFiles.stream().map(m -> m.getId()).collect(Collectors.toList());
            yqGcReceiveEfileMapper.deleteYqGcReceiveEfileByFileIds(fileIds, new YqGcReceiveEfile().getTableName());
        }
        //删除组卷信息
        return yqGcReceiveFolderMapper.deleteYqGcReceiveFolderByIds(ids, new YqGcReceiveFolder().getTableName());
    }

    /**
     * 删除卷内件
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int delFile(String[] ids) {
        List<String> fileIds = Arrays.asList(ids);
        //删除附件
        yqGcReceiveEfileMapper.deleteYqGcReceiveEfileByFileIds(fileIds, new YqGcReceiveEfile().getTableName());
        //删除卷内件信息
        return yqGcReceiveFileMapper.deleteYqGcReceiveFileByIds(ids, new YqGcReceiveFile().getTableName());
    }


    /**
     * 批量新增件的附件
     *
     * @param efileList
     * @param fileId    件的id
     * @param type      1 新增 2 修改
     * @return
     */
    @Transactional
    public int insertEFile(List<YqGcReceiveEfile> efileList, String fileId, String type) {
        //新增不做处理 修改先查询电子件 进行删除 后再进行新增
        if ("2".equals(type)) {
            //查询关联电子件信息
            List<YqGcReceiveEfile> yqGcReceiveEfiles = yqGcReceiveEfileMapper.selectYqGcReceiveEfileByFileId(fileId, new YqGcReceiveEfile().getTableName());
            if (yqGcReceiveEfiles != null && yqGcReceiveEfiles.size() > 0) {
                yqGcReceiveEfileMapper.deleteYqGcReceiveEfileByFileId(fileId, new YqGcReceiveEfile().getTableName());
            }
        }
        efileList.forEach(e -> {
            e.setId(String.valueOf(SnowflakeIdGenerator.generateId()));
            e.setFileId(fileId);
            e.setCreateTime(DateUtils.getNowDate());
            e.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
            yqGcReceiveEfileMapper.insertYqGcReceiveEfile(e, e.getTableName());
        });
        return 1;
    }

    /**
     * 验证卷资料号是否重复
     *
     * @param yqGcReceiveFolder
     * @return
     */
    public Boolean verifyFolder(YqGcReceiveFolder yqGcReceiveFolder) {
        YqGcReceiveFolder folder = new YqGcReceiveFolder();
        //资料号
        folder.setGenNum(yqGcReceiveFolder.getGenNum());
        //册数
        folder.setVolumeNum(yqGcReceiveFolder.getVolumeNum());
        //类号
        folder.setCategoryNum(yqGcReceiveFolder.getCategoryNum());
        List<YqGcReceiveFolder> folders = yqGcReceiveFolderMapper.selectYqGcReceiveFolderList(folder, folder.getTableName());

        if (folders != null && folders.size() > 0) {
            return folders.stream().anyMatch(a -> !a.getId().equals(yqGcReceiveFolder.getId()));
        }
        return false;
    }

    /**
     * 验证件号是否重复
     *
     * @param yqGcReceiveFile
     * @return
     */
    public Boolean verifyFile(YqGcReceiveFile yqGcReceiveFile) {
        YqGcReceiveFile file = new YqGcReceiveFile();
        //件号
        file.setFileNum(yqGcReceiveFile.getFileNum());
        //卷号
        file.setFolderNum(yqGcReceiveFile.getFolderNum());
        List<YqGcReceiveFile> fileList = yqGcReceiveFileMapper.selectYqGcReceiveFileList(file, file.getTableName());
        if (fileList != null && fileList.size() > 0) {
            return fileList.stream().allMatch(a -> !a.getId().equals(yqGcReceiveFile.getId()));
        }
        return false;
    }


    /**
     * 上传附件
     *
     * @param file
     * @return
     */
    @Override
    public R<YqGcReceiveEfile> uploadFile(MultipartFile file) {
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        try {
            // 上传并返回访问地址
            String url = PictureUploadUtils.upload(uplodPath, file);
            YqGcReceiveEfile receiveEfile = new YqGcReceiveEfile();
            receiveEfile.setFieldName(FileUtils.getName(url));
            receiveEfile.setPath(url);
            receiveEfile.setDocFileSize(PictureUploadUtils.bytesTrans(file.getSize()));
            return R.ok(receiveEfile);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 预览
     *
     * @param
     * @return cn.yuanqiao.common.core.domain.R<cn.yuanqiao.common.core.domain.entity.SysFile>
     * @author hbWang
     * @date 2023/9/15 16:26
     */
    @Override
    public byte[] queryImage(String path) {
        String tableCode = SecurityUtils.getTenantCode();
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        uplodPath = uplodPath + path;
        return readFile(uplodPath);
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    private static byte[] readFile(String url) {
        InputStream in = null;
        ByteArrayOutputStream baos = null;
        try {
            // 本机地址
            in = new FileInputStream(url);

            return IOUtils.toByteArray(in);
        } catch (
                Exception e) {

            return null;
        } finally {
            IOUtils.closeQuietly(baos);
        }
    }
}
